unit BufferF;

interface

uses
  RSCOMdec, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls;

type
  TSimMetroPanel = class(TForm)
    Timer1: TTimer;
    GroupBox1: TGroupBox;
    Label1: TLabel;
    laInBuffer: TLabel;
    Label3: TLabel;
    laData: TLabel;
    Label5: TLabel;
    laDataset: TLabel;
    Label2: TLabel;
    laConnection: TLabel;
    procedure ButtonCloseClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);

  private
    { Private-Deklarationen}
  public
    procedure WMCOPYDATA(var msg: TWMCopyData); message WM_COPYDATA;
    function SendIPCData(Data: String): Boolean;
  end;


  TInputRecord = packed record
    Data: string[255];
  end;
  PInputRecord = ^TInputRecord;

  TOutputRecord = packed record
    Data: String[255];
  end;
  POutputRecord = ^TOutputRecord;


var
  SimMetroPanel: TSimMetroPanel;

implementation

{$R *.DFM}

procedure TSimMetroPanel.WMCOPYDATA(var msg: TWMCopyData);

  function HexToInt(HexNum: string): LongInt;
  begin
    Result:=StrToInt('$' + HexNum);
  end;

var
  Data: String;

begin
  Data := String(PInputRecord(msg.CopyDataStruct.lpData)^.Data);
  SendString(PChar(String(Data+#13)));
end;


function TSimMetroPanel.SendIPCData(Data: String): Boolean;
var
  MyRecord: POutputRecord;
  cds: TCopyDataStruct;
  hWnd: THandle;
begin
  GetMem(MyRecord, sizeof(TOutputRecord));
  try
    MyRecord.Data := Data;
    cds.dwData := 0;
    cds.cbData := sizeof(TOutputRecord);
    cds.lpData := MyRecord;
    hWnd := FindWindow('LS1', nil);
    Result := (hWnd = 0);
    SendMessage(hWnd, WM_COPYDATA, Handle, Integer(@cds));
  finally
    FreeMem(MyRecord, sizeof(TOutputRecord));
  end;
end;

procedure TSimMetroPanel.ButtonCloseClick(Sender: TObject);
begin
  CloseCOM;
end;

procedure TSimMetroPanel.FormCreate(Sender: TObject);
begin
  case OpenCOM(PChar('COM1:9600,N,8,1')) of
    0: laConnection.Caption := 'Keine Verbindung';
    1: laConnection.Caption := 'Verbunden';
  end;
  BufferSize (256);
  SendString (PChar('INI1'));
end;

procedure TSimMetroPanel.Timer1Timer(Sender: TObject);
var
  Data: String;
  DataSet: String;
begin
  laInBuffer.Caption := Format('%d Bytes', [InBuffer]);
  Data := ReadString();
  While (Pos('Y', Data) <> 0) and (Pos('X', Data) <> 0) do
  begin
    DataSet := Copy(Data, Pos('X', Data), 9);
    SendIPCData(DataSet);
    laData.Caption := Data;
    laDataset.Caption := Dataset;
    Delete(Data, 1, Pos('Y', Data));
    Application.ProcessMessages;
  end;
end;

end.
